package com.mangowang.lib.common.net.request;


import android.text.TextUtils;

import com.google.protobuf.InvalidProtocolBufferException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.mangowang.lib.common.help.UserHelper;
import com.mangowang.lib.common.net.interfaces.OnRequestCallBack;
import com.mangowang.lib.common.net.interfaces.OnUpLoadCallBack;
import com.mangowang.lib.common.proto.PBPublicOuterClass;
import com.mangowang.lib.common.util.GsonUtils;
import com.mangowang.lib.common.util.LogUtil;
import com.mangowang.lib.common.util.ValidateUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请求模式接口构建模式 1 好商城
 */
public enum RequestModel {

    INSTANCE;

    /**
     * @param api      请求接口
     * @param callBack
     */
    public void post(Object tag, final String api, final Map<String, String> params, final OnRequestCallBack callBack) {
        OkGo.<String>post(api)//
                .tag(tag)
                .params(params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            success(response.body(), api, callBack, params, "post");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        error(response.getException().toString(), api, params, callBack, "post");
                    }

                });

    }

    public void get(Object tag, final String api, final Map<String, String> params, final OnRequestCallBack callBack) {
        if (UserHelper.isLogin()) {//是否登录
            params.put("key", UserHelper.getCurrentToken());
        }
        params.put("client", "android");
        OkGo.<String>get(api)//
                .tag(tag)
                .params(params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            success(response.body(), api, callBack, params, "get");
                        } catch (InvalidProtocolBufferException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        error(response.getException().toString(), api, params, callBack, "get");
                    }

                });

    }

    private void error(String err, String api, Map<String, String> params, OnRequestCallBack callBack, String requestType) {
        if (err.contains("Unable to resolve host")) {
            callBack.onError(-999, "网络连接失败，请检查您的网络");
        } else if (err.contains("Failed to connect") || err.contains("failed to connect")) {
            callBack.onError(-998, "服务器连接失败，请稍后再试或联系客服");
        } else if (err.contains("timed out") || err.contains("timeout")) {
            callBack.onError(-997, "请求超时,请重试");
        } else {
            callBack.onError(-996, "服务器连接失败，请稍后再试或联系客服");
        }
        LogUtil.e("okhttp:", "*---------------------------------------------------------------------------*");
        LogUtil.e("okhttp:", "requestUrl(" + requestType + "-mode1)= " + api);
        LogUtil.e("okhttp:", "isSuccess = 请求错误" + err);
        LogUtil.e("okhttp:", "requestParams： " + GsonUtils.serializedToJson(params));
        LogUtil.e("okhttp:", "response= " + err);
        LogUtil.e("okhttp:", "*                                                                      *");

    }

    private void success(String s, String api, OnRequestCallBack callBack, Map<String, String> params, String requestType) throws InvalidProtocolBufferException {
        LogUtil.e("okhttp:", "*---------------------------------------------------------------------------*");
        LogUtil.e("okhttp:", "requestUrl(" + requestType + "-mode1)= " + api);
        if (s == null) {
            LogUtil.e("okhttp:", "isSuccess = true 数据返回失败");
            print(s, params);
            callBack.onError(-1000, "数据返回空");
            return;
        }
        print(s, params);
        int code = GsonUtils.getIntFromJSON(s, "code");
        if (code == 200) {

            // 解析方法
            LogUtil.e("okhttp:", "isSuccess = true 数据返回正常");
            String result = GsonUtils.getStringFromJSON(s, "result");
            if (TextUtils.isEmpty(result)) {
                callBack.onError(200, GsonUtils.getStringFromJSON(s, "message"));
            } else {
                String[] temp = result.split(",");
                byte[] bytes = new byte[temp.length];
                for (int i = 0; i < temp.length; i++) {
                    bytes[i] = (byte) Integer.parseInt(temp[i]);
                }
                callBack.onOk(bytes);
            }
        } else {
            String msg = GsonUtils.getStringFromJSON(s, "message");
            if ("请登录".equals(msg)) {
                //token失效
                // TODO: 2021/12/8 增加失效弹框
//                MainApplication.showTokenInvalidHint();
                callBack.onError(code, "请登录");
                UserHelper.loginOut();
            } else {
                if (ValidateUtils.isValidate(msg)) {
                    LogUtil.e("okhttp:", "isSuccess = true 数据返回失败:" + msg);
                    callBack.onError(code, msg);
                } else {
                    callBack.onError(code, "数据返回异常:" + msg);
                }
            }
        }
    }

    private void print(String s, Map<String, String> params) {
        LogUtil.e("okhttp:", "requestParams： " + GsonUtils.serializedToJson(params));
        LogUtil.e("okhttp:", "response= " + s);
        LogUtil.e("okhttp:", "*----------------------------------------------------------------------------*");
    }

    public void upLoadFile(final String api, String key, File file, final OnUpLoadCallBack callBack) {
        final Map<String, String> params = new HashMap<>();
        PBPublicOuterClass.PBPublic.Builder builder =  PBPublicOuterClass.PBPublic.newBuilder();
        if (UserHelper.isLogin()) builder.setKey(UserHelper.getCurrentToken());
        builder.setClient("android");
        PBPublicOuterClass.PBPublic public_data = builder.build();
        byte[] bytes= public_data.toByteArray();
        StringBuilder stringBuffer = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            stringBuffer.append((int) bytes[i]).append(",");
        }
        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        params.put("dtp", stringBuffer.toString());




        OkGo.<String>post(api)//
                .isMultipart(true)       // 强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .params(params)        // 这里可以上传参数
                .params(key, file)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String s = response.body();
                        int code = GsonUtils.getIntFromJSON(s, "code");
                        if (code == 200) {
                            LogUtil.e("okhttp:", "isSuccess = 请求成功 数据返回正常");
                            print(s, params);
                            try {
                                callBack.onOk(GsonUtils.getStringFromJSON(s, "result"));
                            } catch (InvalidProtocolBufferException e) {
                                e.printStackTrace();
                            }
                        } else {
                            LogUtil.e("okhttp:", "isSuccess = 请求成功 数据返回失败");
                            print(s, params);
                            callBack.onError(code, GsonUtils.getStringFromJSON(s, "message"));
                        }
                    }

                    @Override
                    public void uploadProgress(Progress progress) {
                        super.uploadProgress(progress);
                        LogUtil.e("Wang", "progress=" + progress.toString());
                        callBack.upProgress((int) (progress.fraction * 100));
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LogUtil.e("Wang", "onUpError=" + response.body());
                        callBack.onError(-1, response.body());
                    }

                });
    }


//    public void upLoadMultiFile(final String api, String key, List<String> upLoadSuccessImages, List<LocalMedia> images, File file, int position, final OnUpLoadCallBack callBack) {
//        final Map<String, String> params = new HashMap<>();
//        PBPublicOuterClass.PBPublic.Builder builder = PBPublicOuterClass.PBPublic.newBuilder();
//        if (UserHelper.isLogin()) builder.setKey(UserHelper.getCurrentToken());
//        builder.setClient("android");
//        PBPublicOuterClass.PBPublic public_data = builder.build();
//        byte[] bytes = public_data.toByteArray();
//        StringBuilder stringBuffer = new StringBuilder();
//        for (int i = 0; i < bytes.length; i++) {
//            stringBuffer.append((int) bytes[i]).append(",");
//        }
//        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
//        params.put("dtp", stringBuffer.toString());
//        OkGo.<String>post(api)//
//                .isMultipart(true)       // 强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
//                .params(params)        // 这里可以上传参数
//                .params(key, file)
//                .execute(new StringCallback() {
//                    @Override
//                    public void onSuccess(Response<String> response) {
//                        String s = response.body();
//                        int code = GsonUtils.getIntFromJSON(s, "code");
//                        if (code == 200) {
//                            LogUtil.e("okhttp:", "isSuccess = 请求成功 数据返回正常");
//                            print(s, params);
//                            try {
//                                String result = GsonUtils.getStringFromJSON(s, "result");
//                                String[] temp = result.split(",");
//                                byte[] bytes = new byte[temp.length];
//                                for (int i = 0; i < temp.length; i++) {
//                                    bytes[i] = (byte) Integer.parseInt(temp[i]);
//                                }
//                                String imageUrl = MemberOuterClass.img_upload.parseFrom(bytes).getImg();
//                                upLoadSuccessImages.add(imageUrl);
//                                int i = position + 1;
//                                if (i == images.size()) {
//                                    StringBuilder UrlBuffer = new StringBuilder();
//                                    for (String url : upLoadSuccessImages) {
//                                        UrlBuffer.append(url).append(",");
//                                    }
//                                    callBack.onOk(UrlBuffer.deleteCharAt(UrlBuffer.length() - 1).toString());
//                                } else {
//                                    upLoadMultiFile(api, key, upLoadSuccessImages, images, new File(images.get(i).getCompressPath()), i, callBack);
//                                }
//                            } catch (InvalidProtocolBufferException e) {
//                                e.printStackTrace();
//                            }
//                        } else {
//                            LogUtil.e("okhttp:", "isSuccess = 请求成功 数据返回失败");
//                            print(s, params);
//                            callBack.onError(code, GsonUtils.getStringFromJSON(s, "message"));
//                        }
//                    }
//
//                    @Override
//                    public void uploadProgress(Progress progress) {
//                        super.uploadProgress(progress);
//                        LogUtil.e("Wang", "progress=" + progress.toString());
//                        callBack.upProgress((int) (progress.fraction * 100));
//                    }
//
//                    @Override
//                    public void onError(Response<String> response) {
//                        super.onError(response);
//                        LogUtil.e("Wang", "onUpError=" + response.body());
//                        callBack.onError(-1, response.body());
//                    }
//
//                });
//    }


}
